/**   
 * @Title: ChooseCityActivity.java 
 * @Package com.jiuyang.baoxian.activity 
 * @Description: TODO(用一句话描述该文件做什么) 
 * @author ChangJianlong   
 * @date 2014-12-17 上午9:20:14 
 * @version V1.0   
 */
package com.bxd.baodan.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.j256.ormlite.dao.Dao;
import com.bxd.baodan.R;
import com.bxd.baodan.app.Constant;
import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.app.LoginInfo;
import com.bxd.baodan.app.SharedPreferanceKey;
import com.bxd.baodan.db.DBHelper;
import com.bxd.baodan.item.CityItem;
import com.bxd.baodan.item.ProvinceItem;
import com.bxd.baodan.item.UserItem;
import com.bxd.baodan.sort.CharacterParser;
import com.bxd.baodan.sort.ClearEditText;
import com.bxd.baodan.sort.PinyinComparator;
import com.bxd.baodan.sort.SideBar;
import com.bxd.baodan.sort.SideBar.OnTouchingLetterChangedListener;
import com.bxd.baodan.sort.SortAdapter;
import com.bxd.baodan.sort.SortModel;
import com.bxd.baodan.util.DialogUtil;
import com.bxd.baodan.util.JSONUtil;
import com.bxd.baodan.util.LogUtil;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.util.NetUtil.RequestStringListener;
import com.bxd.baodan.util.ResourcesUtil;
import com.bxd.baodan.util.SpUtil;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @ClassName: ChooseCityActivity
 * @Description: 选择城市
 * @author ChangJianlong
 * @date 2014-12-17 上午9:20:14
 * 
 */
public class ChooseCityActivity extends BaseActivity {

	private ListView sortListView;
	private SideBar sideBar;
	private TextView dialog;
	private SortAdapter adapter;
	private ClearEditText mClearEditText;
	private List<CityItem> allCities;
	/**
	 * 汉字转换成拼音的类
	 */
	private CharacterParser characterParser;
	private List<SortModel> SourceDateList;

	/**
	 * 根据拼音来排列ListView里面的数据类
	 */
	private PinyinComparator pinyinComparator;
	private String from = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_choose_city);
		setActionBarTitle(ResourcesUtil
				.getStringById(R.string.ab_title_choose_city));

		from = getIntent().getStringExtra("from");
		initViews();
	}

	private void initViews() {
		// 实例化汉字转拼音类
		characterParser = CharacterParser.getInstance();

		pinyinComparator = new PinyinComparator();

		sideBar = (SideBar) findViewById(R.id.sidrbar);
		dialog = (TextView) findViewById(R.id.dialog);
		sideBar.setTextView(dialog);

		// 设置右侧触摸监听
		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

			@Override
			public void onTouchingLetterChanged(String s) {
				// 该字母首次出现的位置
				int position = adapter.getPositionForSection(s.charAt(0));
				if (position != -1) {
					sortListView.setSelection(position);
				}

			}
		});

		sortListView = (ListView) findViewById(R.id.country_lvcountry);
		sortListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Dao<ProvinceItem, ?> dao;
				String proName = "";
				try {
					dao = DBHelper.getInstance(ChooseCityActivity.this).getDao(
							ProvinceItem.class);
					List<ProvinceItem> temp = dao
							.queryBuilder()
							.where()
							.eq("provinceCode",
									((SortModel) adapter.getItem(position))
											.getProCode()).query();
					if (temp != null && temp.size() > 0) {
						proName = temp.get(0).getName();
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}
				/*
				 * 判断来自哪里的地区选择
				 */
				if (from == null) {
					sendRequest(
							proName
									+ " "
									+ ((SortModel) adapter.getItem(position))
											.getName(), ((SortModel) adapter
									.getItem(position)).getCityCode(),
							((SortModel) adapter.getItem(position))
									.getProCode());
					// 这里要利用adapter.getItem(position)来获取当前position所对应的对象
				} else {
					Intent intent = new Intent();
					intent.putExtra("area", proName + " "
							+ ((SortModel) adapter.getItem(position)).getName());
					intent.putExtra("citycode", ((SortModel) adapter
							.getItem(position)).getCityCode());
					intent.putExtra("procode", ((SortModel) adapter
							.getItem(position)).getProCode());
					setResult(RESULT_OK, intent);
					ChooseCityActivity.this.finish();
				}

			}
		});
		// 查询数据库中所有的内容
		allCities = getAllCities();
		if (allCities != null && allCities.size() > 0) {
			// SourceDateList =
			// filledData(getResources().getStringArray(R.array.date));
			SourceDateList = filledData();
		}
		LogUtil.e("-----SourceDateList-----" + SourceDateList);
		// 根据a-z进行排序源数据
		Collections.sort(SourceDateList, pinyinComparator);
		adapter = new SortAdapter(this, SourceDateList);
		sortListView.setAdapter(adapter);

		mClearEditText = (ClearEditText) findViewById(R.id.filter_edit);

		// 根据输入框输入值的改变来过滤搜索
		mClearEditText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
				filterData(s.toString());
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
	}

	private void sendRequest(final String area, final String cityCode,
			final String provCode) {

		NetUtil netUtil = new NetUtil(this, JsonApi.MODIFYINFOR);
		netUtil.setParams("city", cityCode);
		netUtil.setParams("province", provCode);
		netUtil.postRequest("", new RequestStringListener() {

			@Override
			public void onComplete(String result) {
				if (JSONUtil.isSuccess(result)) {
					SpUtil.getInstance().savaString(SharedPreferanceKey.AREA,
							area);

					UserItem item = LoginInfo.getInstance(
							getApplicationContext().getApplicationContext())
							.getUser();
					item.setUe_citycode(cityCode);
					;
					item.setUe_prncode(provCode);
					item.setCity(DBHelper.getInstance(getApplicationContext())
							.getCity(Integer.parseInt(cityCode)).getName());
					LoginInfo.getInstance(getApplicationContext())
							.saveUserInfo(new Gson().toJson(item),
									getApplicationContext());

					ChooseCityActivity.this.sendBroadcast(new Intent(
							Constant.ACTION_SUCCESS_UPLOAD_INFOR));
					ChooseCityActivity.this.finish();
				} else {
					DialogUtil.getInstance().showToast(ChooseCityActivity.this,
							JSONUtil.getMessage(result));
				}
			}
		});

	}

	private List<CityItem> getAllCities() {
		Dao<CityItem, ?> dao;
		try {
			dao = DBHelper.getInstance(this).getDao(CityItem.class);
			List<CityItem> cities = dao.queryBuilder().query();
			return cities;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 为ListView填充数据
	 * 
	 *
	 * @return
	 */
	private List<SortModel> filledData() {
		List<SortModel> mSortList = new ArrayList<SortModel>();

		for (int i = 0; i < allCities.size(); i++) {
			SortModel sortModel = new SortModel();
			sortModel.setProCode(allCities.get(i).getProvinceCode() + "");
			sortModel.setCityCode(allCities.get(i).getCityCode() + "");
			sortModel.setName(allCities.get(i).getName());
			// 汉字转换成拼音
			String pinyin = characterParser.getSelling(allCities.get(i)
					.getName());
			String sortString = pinyin.substring(0, 1).toUpperCase();

			// 正则表达式，判断首字母是否是英文字母
			if (sortString.matches("[A-Z]")) {
				sortModel.setSortLetters(sortString.toUpperCase());
			} else {
				sortModel.setSortLetters("#");
			}

			mSortList.add(sortModel);
		}
		return mSortList;

	}

	/**
	 * 根据输入框中的值来过滤数据并更新ListView
	 * 
	 * @param filterStr
	 */
	private void filterData(String filterStr) {
		List<SortModel> filterDateList = new ArrayList<SortModel>();

		if (TextUtils.isEmpty(filterStr)) {
			filterDateList = SourceDateList;
		} else {
			filterDateList.clear();
			for (SortModel sortModel : SourceDateList) {
				String name = sortModel.getName();
				if (name.indexOf(filterStr.toString()) != -1
						|| characterParser.getSelling(name).startsWith(
								filterStr.toString())) {
					filterDateList.add(sortModel);
				}
			}
		}

		// 根据a-z进行排序
		Collections.sort(filterDateList, pinyinComparator);
		adapter.updateListView(filterDateList);
	}

}
